package cn.wolfcode.shop.cloud.mq;

import cn.wolfcode.shop.cloud.common.BusinessException;
import cn.wolfcode.shop.cloud.domain.OrderInfo;
import cn.wolfcode.shop.cloud.service.ISeckillGoodService;
import cn.wolfcode.shop.cloud.service.ISeckillOrderInfoService;
import org.apache.rocketmq.client.producer.SendCallback;
import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Map;


@Component
@RocketMQMessageListener(
        consumerGroup = MQConstans.CREATE_ORDER_DELAY_GROUP,
        topic = MQConstans.CREATE_ORDER,
        selectorExpression = MQConstans.CREATE_ORDER_DELAY_TAG
)
public class OrderSuccessDelayMQListener implements RocketMQListener<Map> {
    @Autowired
    private ISeckillOrderInfoService seckillOrderInfoService;

    @Autowired
    private ISeckillGoodService seckillGoodService;

    @Autowired
    private RocketMQTemplate rocketMQTemplate;

    @Override
    public void onMessage(Map map) {

        System.out.println("进入延时信息");
        Object seckillId = map.get("seckillId");
        //订单编号
        String orderNo = (String) map.get("data");
        Long goodId = null;
        if (seckillId instanceof Long) {
            goodId = (Long) seckillId;
        } else if (seckillId instanceof Integer) {
            goodId = ((Integer) seckillId).longValue();
        }
        //修改定的状态为超时微支付
        int count = seckillOrderInfoService.changOrderInfoStatus(orderNo, OrderInfo.STATUS_TIMEOUT);
        if (count == 0) {
            //如果没有支付,回补真实库存,回补与库存,修改本地标识
            seckillGoodService.incrCount(goodId);
            seckillGoodService.syncPreCount(goodId);
            rocketMQTemplate.asyncSend(MQConstans.CREATE_ORDER_BRDER_DEST, goodId, new SendCallback() {
                @Override
                public void onSuccess(SendResult sendResult) {
                    System.out.println("发送成功消息");
                }

                @Override
                public void onException(Throwable throwable) {
                    System.out.println("发送成功消息");
                }
            });
        }

    }
}
